import { defineStore } from 'pinia'
import { loginApi } from '@/api/user'
import type { LoginParams, LoginResponse } from '@/api/user/types'
import type { UserState } from './types/types.ts'
import { SET_STORAGE, GET_STORAGE } from '@/utils/storage.ts'
import { constantRoutes } from '@/router/routes'

const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      tentType: '',
      userName: '',
      token: GET_STORAGE('token'),
      menuRoutes: constantRoutes,
      userId: GET_STORAGE('userId') || '',
    }
  },
  actions: {
    async login(data: LoginParams) {
      const res: LoginResponse = await loginApi(data)
      if (res.code === 200) {
        // 存储token
        this.token = res.data.token as string
        SET_STORAGE('token', res.data.token as string)
        SET_STORAGE('userId', res.data.userId as string)
        SET_STORAGE('userName', data.userName as string)
        // 存储用户信息
        this.tentType = res.data.tentType as string
        return 'OK'
      } else {
        return Promise.reject(new Error(res.msg))
      }
    },
  },
})

export default useUserStore
